import React, { useState, useEffect } from 'react'
import { connect } from 'dva'
import { Table, Button, Divider, Popconfirm, Input } from 'antd'
import CustomModal from '../components/CustomModal'
import styles from './index.less'
const Search = Input.Search

const Products = () => {
  // table源数据
  const [data, setData] = useState([])

  // 初始化信息
  useEffect(() => {
    initialize()
  }, [])

  const initialize = () => {
    const newData = []
    for (let i = 0; i < 40; i++) {
      newData.push({
        key: i,
        name: `Edward King ${i}`,
        age: 32,
        address: `London, Park Lane no. ${i}`
      })
    }
    setData(newData)
  }

  // 搜索筛选
  const onSearch = value => {
    const newArr = data.filter(item => item.name.includes(value))
    setData(newArr)
  }

  // 新增信息的modal配置
  const YQCreateCustomModalProps = {
    title: '新增信息',
    onAdd: values => {
      values.key = Date.now()
      setData([...data, values])
    }
  }

  // 编辑信息的modal配置
  const YQEditCustomModalProps = {
    title: '编辑信息',
    onEdit: (values, key) => {
      setData(data.map(item => (item.key === key ? { ...item, ...values } : item)))
    }
  }

  // 刷新页面
  const reload = () => {
    window.location.reload()
  }

  // 删除列
  const onDeleteRow = ({ key }) => {
    const newArr = data.filter(item => item.key !== key)
    setData(newArr)
  }

  // 表头
  const columns = [
    {
      title: 'Name',
      dataIndex: 'name'
    },
    {
      title: 'Age',
      dataIndex: 'age'
    },
    {
      title: 'Address',
      dataIndex: 'address'
    },
    {
      title: 'Action',
      dataIndex: 'action',
      render: (text, record) => (
        <span>
          <CustomModal {...YQEditCustomModalProps} record={record}>
            <Button type="primary">编辑</Button>
          </CustomModal>

          <Divider type="vertical" />

          <Popconfirm title="是否要删除?" onConfirm={() => onDeleteRow(record)}>
            <Button type="primary">删除</Button>
          </Popconfirm>
        </span>
      )
    }
  ]

  return (
    <div className={styles.page_wrap}>
      <div className={styles.title_wrap}>
        <div className={styles.title}>应用类型配置</div>
        <div className={styles.btns}>
          <Button icon="sync" className={styles.sync} onClick={reload}></Button>
          <CustomModal {...YQCreateCustomModalProps}>
            <Button type="primary">新增</Button>
          </CustomModal>
        </div>
      </div>
      <div className={styles.search_wrap}>
        <Search placeholder="Please Enter The name" size="large" enterButton onSearch={onSearch} />
      </div>
      <Table columns={columns} dataSource={data} />
    </div>
  )
}

// export default Products;
export default connect(({ products }) => ({
  products
}))(Products)
